package com.hh.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hh.entity.UserCollection;
import com.hh.es.ProdEs;
import com.hh.service.UserCollectionService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 辉辉
 * @since 2022-08-19
 */
@RestController
@Api(tags = "会员的收藏管理接口")
@RequestMapping("/p/user/collection")
public class UserCollectionController {

    @Resource
    private UserCollectionService userCollectionService;

    @GetMapping("/count")
    @ApiOperation("查询用户收藏的数量")
    public ResponseEntity<Integer> getCollectCount() {
        String openId = SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString();
        int count = userCollectionService.count(Wrappers.<UserCollection>lambdaQuery()
                .eq(UserCollection::getUserId, openId)
        );
        return ResponseEntity.ok(count);
    }

    @GetMapping("/prods")
    @ApiOperation("分页查询用户收藏的商品")
    public ResponseEntity<IPage<ProdEs>> findUserCollectionProd(Page<UserCollection> page) {
        String openId = SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString();
        IPage<ProdEs> prodEsIPage = userCollectionService.findUserCollectionProd(page, openId);
        return ResponseEntity.ok(prodEsIPage);
    }

    @GetMapping("/isCollection")
    @ApiOperation("查询用户是否收藏该商品")
    public ResponseEntity<Boolean> isCollection(Long prodId) {
        String openId = SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString();
        Boolean flag = userCollectionService.findUserIsCollection(prodId, openId);
        return ResponseEntity.ok(flag);
    }

    @PostMapping("/addOrCancel")
    @ApiOperation("用户添加或者取消收藏商品")
    public ResponseEntity<Void> addOrCancel(@RequestBody Long prodId) {
        String openId = SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString();
        userCollectionService.addOrCancelCollection(prodId, openId);
        return ResponseEntity.ok().build();
    }
}

